// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.warehouse.dbmanager.ui;

import java.util.List;

import org.dengues.commons.sql.data.DataSetRow;
import org.dengues.commons.ui.swt.table.TableViewerWithMultipage;
import org.dengues.warehouse.i18n.Messages;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.dialogs.SearchPattern;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 1 2006-09-29 17:06:40Z qiang.zhang $
 * 
 */
public class DataEditorComposite extends AbstractEditorComposite {

    private DatabaseManagerDialog dialog;

    private Tree defaultTree;

    private TableViewerWithMultipage treeViewer;

    private Text itemsRow;

    private Text nameFilter;

    private CCombo fieldFilter;

    /**
     * Qiang.Zhang.Adolf@gmail.com DataEditorComposite constructor comment.
     * 
     * @param parent
     */
    public DataEditorComposite(Composite parent) {
        super(parent, SWT.NONE);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.warehouse.dbmanager.ui.AbstractEditorComposite#initComponents()
     */
    @Override
    protected void initComponents() {
        Composite composite = new Composite(this, SWT.NONE);
        GridLayout gridLayout = new GridLayout(3, false);
        gridLayout.marginBottom = 0;
        gridLayout.marginWidth = 0;
        gridLayout.marginTop = 0;
        gridLayout.marginRight = 0;
        gridLayout.marginLeft = 0;
        gridLayout.marginHeight = 0;

        gridLayout.horizontalSpacing = 5;
        gridLayout.verticalSpacing = 0;
        composite.setLayout(gridLayout);
        createToolBar(DATA, composite);
        Label label = new Label(composite, SWT.SEPARATOR | SWT.VERTICAL);
        GridData gid = new GridData();
        gid.heightHint = coolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
        label.setLayoutData(gid);
        createRowNumComposite(composite);
        createTable();
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "createNameFilterComposite".
     * 
     * @param composite
     */
    private void createNameFilterComposite(Composite composite) {
        Label label = new Label(composite, SWT.NONE);
        label.setText(Messages.getString("DataEditorComposite.filter.field")); //$NON-NLS-1$
        fieldFilter = new CCombo(composite, SWT.READ_ONLY | SWT.BORDER);
        GridData gridData = new GridData(GridData.FILL_BOTH);
        gridData.minimumWidth = 60;
        fieldFilter.setLayoutData(gridData);
        label = new Label(composite, SWT.NONE);
        label.setText(Messages.getString("DataEditorComposite.condition")); //$NON-NLS-1$
        nameFilter = new Text(composite, SWT.BORDER);
        nameFilter.setToolTipText(Messages.getString("DataEditorComposite.enter.tip")); //$NON-NLS-1$
        gridData = new GridData(GridData.FILL_BOTH);
        gridData.minimumWidth = 80;
        nameFilter.setLayoutData(gridData);
        nameFilter.setText("*"); //$NON-NLS-1$
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "createRowNumComposite".
     * 
     * @param composite
     */
    private void createRowNumComposite(Composite composite) {
        GridLayout gridLayout;
        Composite composite2 = new Composite(composite, SWT.RIGHT);
        gridLayout = new GridLayout(6, false);
        gridLayout.marginBottom = 0;
        gridLayout.marginWidth = 0;
        gridLayout.marginTop = 0;
        gridLayout.marginRight = 0;
        gridLayout.marginLeft = 0;
        gridLayout.marginHeight = 0;

        gridLayout.horizontalSpacing = 0;
        gridLayout.verticalSpacing = 0;
        composite2.setLayout(gridLayout);

        createNameFilterComposite(composite2);

        Label label = new Label(composite2, SWT.NONE);
        label.setText(Messages.getString("DataEditorComposite.row")); //$NON-NLS-1$
        itemsRow = new Text(composite2, SWT.BORDER);
        GridData gridData = new GridData(GridData.FILL_VERTICAL);
        gridData.widthHint = 30;
        itemsRow.setLayoutData(gridData);
        itemsRow.setText("10"); //$NON-NLS-1$

    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "createTable".
     */
    private void createTable() {
        treeViewer = new TableViewerWithMultipage(this);
        defaultTree = treeViewer.getTree();
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "updateDefaultTable".
     * 
     * @param colNames
     * @param data
     */
    public void updateDefaultTable(String[] colNames, List<DataSetRow> data) {
        if (defaultTree != null && !defaultTree.isDisposed()) {
            fieldFilter.setItems(colNames);
            if (colNames.length > 0) {
                fieldFilter.select(0);
            }
            if (data != null && treeViewer.getTreeViewer().getFilters().length == 0) {
                treeViewer.getTreeViewer().addFilter(viewerFilter);
            }
            treeViewer.setInput(colNames, data, Integer.parseInt(itemsRow.getText()));
            // resize all the columns but not the table
            for (int i = 0; i < defaultTree.getColumnCount(); i++) {
                defaultTree.getColumn(i).pack();
            }
            // scroll to show the first col and first row
            if (defaultTree.getItems().length > 0) {
                defaultTree.showItem(defaultTree.getItem(0));
                if (defaultTree.getColumns() != null && defaultTree.getColumns().length > 0) {
                    defaultTree.showColumn(defaultTree.getColumn(0));
                }
            }
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.warehouse.dbmanager.ui.AbstractEditorComposite#getDialog()
     */
    @Override
    public DatabaseManagerDialog getDialog() {
        return this.dialog;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.warehouse.dbmanager.ui.AbstractEditorComposite#getSqlText()
     */
    @Override
    public String getSqlText() {
        return null;
    }

    /**
     * Sets the dialog.
     * 
     * @param dialog the dialog to set
     */
    public void setDialog(DatabaseManagerDialog dialog) {
        this.dialog = dialog;
    }

    /**
     * Getter for tableViewer.
     * 
     * @return the tableViewer
     */
    @Override
    public TableViewerWithMultipage getTableViewer() {
        return this.treeViewer;
    }

    ViewerFilter viewerFilter = new ViewerFilter() {

        @Override
        public boolean select(Viewer viewer, Object parentElement, Object element) {
            SearchPattern searchPattern = new SearchPattern();
            searchPattern.setPattern(nameFilter.getText());
            String colName = fieldFilter.getText();
            int colIndex = 0;
            if (element instanceof DataSetRow) {
                DataSetRow row = (DataSetRow) element;
                for (int i = 0; i < defaultTree.getColumnCount(); i++) {
                    if (defaultTree.getColumn(i).getText().equals(colName)) {
                        colIndex = i;
                        break;
                    }
                }
                return searchPattern.matches(row.getObjectValue(colIndex - 1).toString());
            }
            return false;
        }

    };

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.warehouse.dbmanager.ui.AbstractEditorComposite#addListener()
     */
    @Override
    protected void addListeners() {
        defaultTree.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                int length = defaultTree.getSelection().length;
                if (length > 0) {
                    addRowAction.setEnabled(true);
                    removeRowAction.setEnabled(true);
                }
            }

        });

        nameFilter.addModifyListener(new ModifyListener() {

            public void modifyText(ModifyEvent e) {
                treeViewer.getTreeViewer().refresh();
            }
        });
    }

}
